package net.anzix.jimposition.transformations;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.swing.JPanel;
import net.anzix.jimposition.BasicTransformation;
import net.anzix.jimposition.Plugin;

@Plugin
public class PageFilter extends BasicTransformation {
//    private Logger logger = Logger.getLogger(PageFilter.class);
    private PageFilterPanel panel = new PageFilterPanel();

    public byte[] alter(byte[] input) {
        try {
            PdfReader inputReader = new PdfReader(input);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            int maxPageNum = inputReader.getNumberOfPages();
            Rectangle oldPageSize = inputReader.getPageSize(maxPageNum - 1);
//            logger.debug(pageSize.left()+" "+pageSize.right()+" "+pageSize.top()+" "+pageSize.bottom());
            Rectangle pageSize = new Rectangle(oldPageSize.width(), oldPageSize.height());
            //           logger.debug(pageSize.left()+" "+pageSize.right()+" "+pageSize.top()+" "+pageSize.bottom());
            Document document = new Document(pageSize);
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);
            document.open();
            int pagenum = 1;

            String filter = getAttribute("pages").toString();
            for (int page = 1; page < maxPageNum; page++) {
                if (!isValidPage(page, filter)) {
                    continue;
                }
                document.newPage();
                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate template = writer.getImportedPage(inputReader, page);
                cb.addTemplate(template, -1 * template.getBoundingBox().left(), -1 * template.getBoundingBox().bottom());
                cb.stroke();
            }
            document.close();
            return outputStream.toByteArray();
        } catch (DocumentException ex) {
            ex.printStackTrace();
            return null;
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }

    }

    public String toString() {
        return "Select pages";
    }

    public boolean isValidPage(int page, String filter) {
        if (filter.startsWith("%")) {
            return filter.equals("%0") && (page % 2 == 0) || filter.equals("%1") && (page % 2 == 1);
        }


        boolean result = true;
        String interval[] = filter.split("-");
        if (interval.length > 0 && interval[0].length() > 0) {
            try {
                int begin = Integer.parseInt(interval[0]);
                if (begin <= page) {
                    result = true;
                } else {
                    result = false;
                }
            } catch (NumberFormatException ex) {
                result = false;
            }
        }
        if (interval.length > 1 && interval[1].length() > 0) {
            try {
                int end = Integer.parseInt(interval[1]);
                if (end >= page) {
                    result = result & true;
                } else {
                    result = false;
                }
            } catch (NumberFormatException ex) {
                result = false;
            }
        }
        return result;
    }

    public JPanel getPanel() {
        return panel;
    }

    public void setPanelSettings() {
        panel.getSelectedPages().setText(getAttribute("pages").toString());
    }

    public void getPanelSettings() {
        setAttribute("pages", panel.getSelectedPages().getText());
    }
}
